package com.yuejie.musicai.services.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.yuejie.musicai.db.DBConnection;
import com.yuejie.musicai.beans.Info;
import com.yuejie.musicai.log.LogLevelEnum;
import com.yuejie.musicai.log.LogServiceImpl;
import com.yuejie.musicai.services.AccountService;
import com.yuejie.musicai.util.MD5Util;

@Service
public class AccountServiceImpl implements AccountService {

	@Override
	public Info login(String user,String password) {
		
		DBConnection db = new DBConnection();
		
		String result = "success";
		String psn_password = "";
		Object[] params = new Object[]{user};
		Info info = new Info();
		try
		{
			List<Map<String, Object>> list = db.querySMSInfo(SELECT_SQL, params);
			if(list == null || list.size() == 0)
			{
				result = "invailduser";
			}
			else
			{
				Map<String, Object> map = list.get(0);
				psn_password = (String)map.get("psn_password");
				String paramPass =  MD5Util.MD5(password);
				
				if(!psn_password.equals(paramPass))
				{
					result = "invaildpassword";
				}
			}
		}
		catch(Exception e) 
		{
			result = "failed";
			LogServiceImpl.log(LogLevelEnum.ERROR, e.toString());
		}
		finally
		{
			if(db != null) {
				db.close();
			}
		}
		info.setMessage(result);
		
		return info;
	}

	@Override
	public Info creatuser(String user,String password) {
		DBConnection db = new DBConnection();
		
		String result = "failed";
		String psn_password = MD5Util.MD5(password);
		Object[] params = new Object[]{user, psn_password};;
		List<Object[]> paramList = new ArrayList<Object[]>();
		
		paramList.add(params);
		
		boolean flag = true;
		Info info = new Info();
		try
		{
			if(judgePerson(user, db))
			{
				 flag = db.insertSMSInfo(INSERT_SQL, paramList); 
				 if(flag)
				 {
					 result = "success";
				 }
			}
			else
			{
				result = "duplicated";
			}
		}
		catch(Exception e) 
		{
			result = "failed";
			LogServiceImpl.log(LogLevelEnum.ERROR, e.toString());
		}
		finally
		{
			if(db != null)
			{
			    db.close();
			}
		}
		
		info.setMessage(result);
		
		return info;
	}
	
	public boolean judgePerson(String psn_account, DBConnection db) throws Exception
	{
		Object[] params = new Object[]{psn_account};
		List<Map<String, Object>> list = db.querySMSInfo(SELECT_SQL, params);
		
		if(list != null && list.size() != 0) 
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	private final static String INSERT_SQL = "INSERT INTO person(psn_account, psn_password) VALUES(?, ?)";
	
	
	private final static String SELECT_SQL = "SELECT psn_account, psn_password FROM person WHERE psn_account = ?";

}
